/**
 * Created by Administrator on 2017/3/7.
 */
import React from 'react';
import { Modal } from 'antd';
import './tiku_list.css';
import {browserHistory,Link} from "react-router";
function error1() {
    Modal.error({
        title: '警告',
        content: '请勾选一题',
    });
}
function error2() {
    Modal.error({
        title: '警告',
        content: '每次只能编辑一题，请重新选择',
    });
}
class Tiku extends React.Component{
    constructor(){
        super();
        this.state={result:"",check:false};
    }
    // change=(e)=>{
    //     console.log(e.target.checked);
    //   this.setState({check:e.target.checked});
    // };
    render(){
        var _this=this;
            return <div>
                <div className="J_section">
                    <div>
                        <div>
                            <div className="J_search">
                                <label htmlFor="search">搜索：</label>
                                <input placeholder="请输入关键字" type="text" id="search"/>
                                <span></span>
                            </div>
                            <div className="J_func">
                                <span className="J_add" onClick={()=>{browserHistory.push('/question/add')}}> 新增</span>
                                <span className="J_edit" >编辑</span>
                                <span className="J_copy">复制</span>
                                <span className="J_remove">移动</span>
                                <span className="J_delete">删除</span>
                            </div>
                        </div>
                        <div className="J_sort">
                            <span data-1="a.create_date asc" data-2="a.create_date desc">创建时间 <em data-1="asc" className="J_down"></em></span>
                            <span data-1="a.update_date asc" data-2="a.update_date desc">更新时间 <em data-1="desc" className=""></em></span>
                            <span data-1="a.error_rate asc" data-2="a.error_rate desc">错误率 <em data-1="desc" className=""></em></span>
                            <div>
                                <select data-1="difficulty" defaultValue={3}>
                                    <option value="3" disabled>难度</option>
                                    <option value="">全部</option>
                                    <option value="0">易</option>
                                    <option value="1">中</option>
                                    <option value="2">难</option>
                                </select>
                            </div>
                            <div>
                                <select data-1="problemType" defaultValue={3}>
                                    <option value="3" disabled>题型</option>
                                    <option value="">全部</option>
                                    <option value="0">单选题</option>
                                    <option value="1">多选题</option>
                                    <option value="2">判断题</option>
                                </select>
                            </div>
                            <div>
                                <select>
                                    <option>内容</option>
                                    <option>全部</option>
                                    <option>仅文字</option>
                                    <option>附图片</option>
                                    <option>附视频</option>
                                    <option>附音频</option>
                                </select>
                            </div>
                        </div>
                        <div className="J_content">
                            {
                                this.state.result===""?"":this.state.result.data.list.map(function (result,index) {
                                        return  <div className="title" key={index}>
                                            <label htmlFor={"checkbox"+index} ></label>
                                            <input id={"checkbox"+index} name='isSelect' type="checkbox"/>
                                            <input type="hidden" value={result.id} name="id"/>
                                            <span><em style={{background:"#fff"}}>{index+1}.</em>
                                                <em>{result.problemType==='0'?"单选题":result.problemType==='1'?"多选题":"判断题"}</em>
                                                <em>{result.difficulty==='0'?"易":result.difficulty==='1'?"中":"难"}</em>
                                                <em>{result.errorRate==='0'?0:result.errorRate*100+"%"}</em>
                                                <em>{result.createDate}</em></span>
                                            <span className="J_btn"><b>展开</b> <i className="J_down"></i></span>
                                            <div className="J_text" dangerouslySetInnerHTML={{__html:result.contents}}></div>
                                            <div className="J_drop J_close">
                                                {
                                                    result.itemJson===""?"":JSON.parse(result.itemJson).map(function (result,index) {
                                                            return  <div key={index}>
                                                                <span>{result.numberIndex}.</span>
                                                                <div dangerouslySetInnerHTML={{__html:result.content}}></div>
                                                            </div>
                                                        })}
                                                <div>
                                                    <span>答案：</span>
                                                    <span>{result.result==="1"?"对":result.result==="0"?"错":result.result}</span>
                                                </div>
                                                <div>
                                                    <span>解析：</span>
                                                    <div dangerouslySetInnerHTML={{__html:result.notes}}></div>
                                                </div>
                                            </div>
                                        </div>
                                    })
                            }
                        </div>
                    </div>
                    <div className="J_select">
                        <label htmlFor="checkboxAll" ></label>
                        <input id="checkboxAll" className="checkboxAll" type="checkbox"/> 全选
                        <div>
                            <span>共 <em>{this.state.result===""?"0":this.state.result.data.count}</em> 条记录</span>
                            <span className={this.state.result===""?"J_fy J_Left J_No":
                                this.state.result.data.pageNo===1?"J_fy J_Left J_No":"J_fy J_Left "}></span>
                            <span className={this.state.result===""?"J_fy J_left J_no":
                                this.state.result.data.pageNo===1?"J_fy J_left J_no":"J_fy J_left"}></span>
                            <em>第</em>
                            <div className="J_selects">
                                <span></span>
                                <select></select>
                            </div>
                            <em>共 {this.state.result===""?"0":this.state.result.data.last} 页</em>
                            <span className={this.state.result===""?"J_fy J_right":
                                this.state.result.data.pageNo===this.state.result.data.last?
                                    "J_fy J_right":"J_fy J_right J_have"}></span>
                            <span className={this.state.result===""?"J_fy J_Right":
                                this.state.result.data.pageNo===this.state.result.data.last?
                                    "J_fy J_Right":"J_fy J_Right J_Have"}></span>
                        </div>
                    </div>
                </div>
            </div>
    };

    componentDidMount(){
        var _this=this;
        /**判断是否为json数组**/
        function isJSON (str) {
            str = str.replace(/\s/g, '').replace(/\n|\r/, '');
            if (/^\{(.*?)\}$/.test(str))
                return /"(.*?)":(.*?)/g.test(str);
            if (/^\[(.*?)\]$/.test(str)) {
                return str.replace(/^\[/, '')
                    .replace(/\]$/, '')
                    .replace(/},{/g, '}\n{')
                    .split(/\n/)
                    .map(function (s) { return isJSON(s); })
                    .reduce(function (prev, curr) { return !!curr; });
            }
            return false;
        }
        /**没有数据，页面显示0页***/
        if(!_this.state.result){
            $(".J_selects>select").html("<option>0</option>");
        }
        /**初次加载渲染页面**/
        $.ajax({
            type:"GET",
            // url:"http://192.168.2.9:8080/learn/s/resources/hProblems",
            url:"http://192.168.2.9:8080/learn/s/resources/hProblems",
            success:function (result) {
                if(result.data.list){
                    $.each(result.data.list,function (index,p) {
                        if(p.itemJson==='[]'){
                            result.data.list[index].itemJson="";
                        }else if(!p.itemJson){
                            result.data.list[index].itemJson="";
                        }else {//判断是否是json数组
                            if(!isJSON(p.itemJson)){
                                result.data.list[index].itemJson="";
                            }
                        }

                    });
                    _this.setState({result:result});
                    /*****将页码拼接到页面******/
                    var _html='';
                    for(var i=1;i<=result.data.last;i++){
                        _html+=' <option value="'+i+'">'+i+'</option>'
                    }
                    $(".J_selects>select").html(_html);
                    Event()
                }else {
                   return
                }
            }
            });
        /**每次触发事件改变状态重新渲染页面**/
        var _param={};
        function ajax() {
            $.ajax({
                type:"POST",
                data:_param,
                // url:"http://192.168.2.9:8080/learn/s/resources/hProblems",
                 url:"http://192.168.2.9:8080/learn/s/resources/hProblems",
                success:function (result) {
                    if(result.data.list){//有数据
                        $.each(result.data.list,function (index,p) {
                            if(p.itemJson==='[]'){
                                result.data.list[index].itemJson="";
                            }else if(!p.itemJson){
                                result.data.list[index].itemJson="";
                            }else {//判断是否是json数组
                                if(!isJSON(p.itemJson)){
                                    result.data.list[index].itemJson="";
                                }
                            }
                        });
                        _this.setState({result:result,check:false});
                        /**拼接页码**/
                        var _html;
                        for(var i=1;i<=result.data.last;i++){
                            _html+=' <option value="'+i+'">'+i+'</option>'
                        }
                        $(".J_selects>select").html(_html);
                        /***每次渲染，题目选项默认收缩**/
                        $(".J_content>.title>.J_drop").addClass('J_close');
                         $('.J_content .title .J_btn').children('b').text('展开')
                    .next().attr('class','J_down');
                    }else {//没有数据
                        _this.setState({result:"",check:false});
                        $(".J_selects>select").html("<option>0</option>");
                    }
                    $(":checkbox").prop('checked',false).siblings('label').removeClass('J_color');//每次渲染清空选中项
                    $('.J_selects>select [value='+_this.state.result.data.pageNo+']').prop('selected',true)
                        .siblings().prop('selected',false);//每次渲染默认选择第一页
                }
            });
        }
        /*******页面所有事件*********/
       function Event() {
           /***编辑**/
           $('.J_func').on('click','.J_edit',function () {
                var _count=$('.J_content .title input:checked').length;
                if(_count<1){
                    error1();
                }else if(_count>1){
                    error2();
                }else{
                    var _id=$('.J_content .title input:checked').next().val();
                    browserHistory.push('/question/revise/'+_id);
                }
           });
           /*****点击展开/收缩*****/
            $(".J_content ").on('click','.title .J_btn',function () {
               $(this).siblings('.J_drop').toggleClass("J_close");
               if($(this).children('b').text()==="展开"){
                   $(this).children('b').text('收起').next().attr('class','J_up');
               }else if($(this).children('b').text()==="收起"){
                   $(this).children('b').text('展开').next().attr('class','J_down');
               }
             });
           /*****排序*****/
                /*******按默认、跟新时间、错误率排序*********/
            $(".J_sort").on('click','>span',function () {
                var _data;
                $(this).siblings().children('em').attr('class','');
                if($(this).children('em').attr('data-1')==='asc'){
                     _data=$(this).attr('data-1');
                    $(this).children('em').attr({'data-1':'desc','class':"J_up"});
                }else if($(this).children('em').attr('data-1')==='desc'){
                    _data=$(this).attr('data-2');
                    $(this).children('em').attr({'data-1':'asc','class':"J_down"});
                }
                // $('.J_content .title .J_btn').children('b').text('展开')
                //     .next().attr('class','J_down');
                _param.orderBy =_data;
                ajax();
            });
           /*******按题型，难度，内容排序*********/
            $(".J_sort").on('change','select',function () {
                var _type=$(this).attr('data-1');
                _param.pageNo='';
               if(_type==='problemType'){
                   _param.problemType=$(this).val();
               }else if(_type==='difficulty'){
                   _param.difficulty=$(this).val();
               }
                ajax()
            });
           /*******搜索*******/
           $(".J_search>span").click(function () {
               var _value=$(this).prev().val();
               _param.searchCondition=_value;
               ajax();
           });
           /***分页***/
           $(".J_selects>select").change(function () {
               _param.pageNo=$(this).val();
               ajax();
           });
            $(".J_select>div>.J_fy").click(function () {
                var pagenow=_this.state.result.data.pageNo;
                var last=_this.state.result.data.last;
                if($(this).hasClass('J_right')&&$(this).hasClass('J_have')){//下一页
                    pagenow++;
                }else if($(this).hasClass('J_Right')&&$(this).hasClass('J_Have')){//尾页
                    pagenow=last;
                }else if($(this).hasClass('J_left')&&!$(this).hasClass('J_no')){//上一页
                    pagenow--;
                }else if($(this).hasClass('J_Left')&&!$(this).hasClass('J_No')){//首页
                    pagenow=1;
                }else {
                    if(pagenow===1||pagenow===last){
                        return
                    }
                }
                // if(pagenow>1&&pagenow<last){
                //     $(".J_select>div>.J_Left").removeClass('J_No');
                //     $(".J_select>div>.J_left").removeClass('J_no');
                //     $(".J_select>div>.J_Right").addClass('J_Have');
                //     $(".J_select>div>.J_right").addClass('J_have');
                // }else if(pagenow===last){
                //     $(".J_select>div>.J_Right").removeClass('J_Have');
                //     $(".J_select>div>.J_right").removeClass('J_have');
                //     $(".J_select>div>.J_Left").removeClass('J_No');
                //     $(".J_select>div>.J_left").removeClass('J_no');
                // }else if(pagenow===1){
                //     $(".J_select>div>.J_Left").addClass('J_No');
                //     $(".J_select>div>.J_left").addClass('J_no');
                //     $(".J_select>div>.J_Right").addClass('J_Have');
                //     $(".J_select>div>.J_right").addClass('J_have');
                // }
                _param.pageNo=pagenow;
                ajax();
            });
            /**全选**/
            $(".J_select").on('click','.checkboxAll',function () {
                   if(this.checked){
                       $('.J_content .title > label').addClass('J_color');
                   }else {
                       $('.J_content .title > label').removeClass('J_color');
                   }
                   $("[name=isSelect]:checkbox").prop("checked", this.checked);
                   $(this).prev().toggleClass('J_color');
            });
            /*复择框*/
            $(".J_content").on('click',':checkbox',function () {
                var flag = true;
                $(this).prev().toggleClass('J_color');
                $(".J_content :checkbox").each(function () {
                    var checked=$(this).prop('checked');
                    if (!checked) {
                        flag = false;
                    }
                });
                if(flag){
                    $(".checkboxAll").prev().addClass('J_color');
                } else{
                    $(".checkboxAll").prev().removeClass('J_color');
                }
                $(".checkboxAll").prop("checked", flag);
            });
        }

    }
}
export default Tiku;
